package com.woniu.custom.webscoket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ServerEndpoint(value = "/websocket/{from}/{to}")
@Component
public class WebSocketServer {
    private static Logger L = LoggerFactory.getLogger(WebSocketServer.class);

    private static List<SessionWrap> sessionList = new ArrayList<>();
    private String from;
    private String to;


    /**
     * 连接建立成功
     * @param session
     * @param
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("from") String from, @PathParam("to") String to) throws IOException {
        System.out.println("连接成功");
        System.out.println(from);
        System.out.println(to);
        session.getBasicRemote().sendText("正在排队请稍等...");
        this.from = from;
        this.to = to;
        for(SessionWrap item : sessionList){
            if(item.getFrom().equals(from) && item.getTo().equals(to)){
                item.setSession(session);
                item.setLastTime(new Date());
                return ;
            }
        }
        SessionWrap sessionWrap = new SessionWrap();
        sessionWrap.setFrom(from);
        sessionWrap.setTo(to);
        sessionWrap.setSession(session);
        sessionWrap.setLastTime(new Date());
        sessionList.add(sessionWrap);
    }

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose() {
        System.out.println("关闭");
        List<SessionWrap> newSessionList = new ArrayList<>();
        for(SessionWrap item : sessionList){
            if(item.getFrom().equals(from) && item.getTo().equals(to)){
                continue;
            }
            newSessionList.add(item);
        }
        sessionList = newSessionList;
    }

    /**
     * 接收消息
     * @param message
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        try {
            //发送到对方
            for(SessionWrap item : sessionList){
                if(item.getFrom().equals(to) && item.getTo().equals(from)){
                    item.getSession().getBasicRemote().sendText(message);
                    break;
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
